import {toast} from "../../utils/tool";
import {COUPON_ENUM} from "../../constant/index";

const app = getApp();

Page({
    data: {
        list: [],
    },
    formatDate(time) {
        const date = new Date(time * 1000)
        const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
        return `${year}-${month < 10 ? '0' + month : month}-${day >= 10 ? day : '0' + day}`
    },
    initData() {
        app.ajax({
            url: '/api/user/coupons',
            success: resp => {
                const {code, data, msg} = resp
                if (code !== 1) {
                    return toast({
                        title: msg
                    }, () => {
                        wx.navigateBack()
                    })
                }
                if (data && data.length) {
                    this.setData({
                        list: data.map(item => {
                            const createTime = this.formatDate(item['create_time'])
                            return {
                                ...item,
                                createTime,
                            }
                        })
                    })
                }
            }
        })
    },
    onLoad: function (options) {
        // this.initData()
        const {globalData: {couponData}} = app

        this.setData({
            list: couponData[COUPON_ENUM.COUPON].map(item =>{
                const createTime = this.formatDate(item['create_time'])
                return {
                    ...item,
                    createTime,
                }
            })
        })
    }
});